package com.yc.cloud.sms.sevice.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import com.yc.cloud.sms.config.TencentSmsProperties;
import com.yc.cloud.sms.dto.SmsParam;
import com.yc.cloud.sms.response.SmsResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("tencentSmsService")
public class TencentSmsServiceImpl extends AbstractSmsService {

    @Resource
    private TencentSmsProperties tencentSmsProperties;

    @Override
    protected SmsResponse doSend(SmsParam param) {
        try {
            Credential cred = new Credential(tencentSmsProperties.getId(), tencentSmsProperties.getKey());
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-shanghai", clientProfile);

            SendSmsRequest req = new SendSmsRequest();
            req.setSmsSdkAppid(tencentSmsProperties.getAppId());
            req.setSign(tencentSmsProperties.getSign());
            req.setTemplateID(param.getTemplateId());
            String[] phoneNumbers = { tencentSmsProperties.getCoutry() + param.getMobile() };
            req.setPhoneNumberSet(phoneNumbers);
            req.setTemplateParamSet(param.getTemplateParams());

            var res = client.SendSms(req);
            SendStatus sendStatus = res.getSendStatusSet()[0];
            String smsCode = sendStatus.getCode();

            if ("Ok".equals(smsCode)) {
                return SmsResponse.builder().success(true).build();
            }
            log.error("腾讯云短信发送失败: {}", getSMSErrorMsg(smsCode));
            return SmsResponse.builder().success(false).errorCode(smsCode).errorMessage(getSMSErrorMsg(smsCode))
                    .build();
        } catch (Exception e) {
            log.error("腾讯云短信发送异常", e);
            return SmsResponse.builder().success(false).errorCode("500").errorMessage(e.getMessage()).build();
        }
    }

    @Override
    public String getProvider() {
        return "tencent";
    }

    private String getSMSErrorMsg(String smsCode) {
        if ("LimitExceeded.PhoneNumberDailyLimit".equals(smsCode)) {
            return "抱歉,今日发送验证码的次数达到上限";
        }
        return "短信发送失败,原因为:" + smsCode;
    }
}